<template>
  <SearchCollapse :mixHeight="32">
    <el-form
      ref="searchRef"
      class="global-search-form"
      :inline="true"
      :model="formData"
    >
      <el-form-item label="" prop="keyword">
        <el-input
          v-model="formData.keyword"
          placeholder="昵称/姓名/手机号/OwnID/Unique"
          style="width: 240px"
        ></el-input>
      </el-form-item>
      <el-form-item label="" prop="createTimeRange">
        <el-date-picker
          v-model="formData.createTimeRange"
          type="daterange"
          value-format="x"
          :editable="false"
          :disabled-date="datePicker.disabledDate"
          :shortcuts="datePicker.shortcuts"
          start-placeholder="请选择"
          end-placeholder="充值时间"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="" prop="type">
        <el-select v-model="formData.type" placeholder="充值类型">
          <el-option label="结算状态" value></el-option>
          <el-option
            v-for="item in getCapitalTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #control>
      <el-button
        type="primary"
        :icon="Search"
        :loading="props.isLoading"
        @click="handleClickSearch"
        >查询</el-button
      >
      <PipeResetBtn :formEl="searchRef" @clear="handleClickSearch"
        >取消</PipeResetBtn
      >
    </template>
  </SearchCollapse>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { Search } from '@element-plus/icons-vue';
import type { ElForm } from 'element-plus';
import { GetStateOptions } from '@/utils/common';
import { useRoute, onBeforeRouteUpdate } from 'vue-router';
import { InitDatePickerOpts } from '@/utils/common-picker';

// 日期选择器
const datePicker = InitDatePickerOpts();

// 路由
const route = useRoute();

const getCapitalTypeOptions = GetStateOptions('recharge-type');

// 表单ref
const searchRef = ref<InstanceType<typeof ElForm>>();

// 查询数据
const formData = reactive({
  keyword: '',
  type: '',
  createTimeRange: []
});

// props
const props = defineProps({
  isLoading: {
    type: Boolean,
    default: false
  }
});

// emits
const emits = defineEmits(['onSearch']);

// 搜索
const handleClickSearch = () => {
  // 获取查询条件
  const dataOpt: any = {};
  for (const [key, val] of Object.entries(formData)) {
    if (val !== '') dataOpt[key] = val;
  }

  dataOpt.createTimeStart = dataOpt.createTimeRange?.[0] || undefined;
  dataOpt.createTimeEnd = dataOpt.createTimeRange?.[1] || undefined;
  delete dataOpt.createTimeRange;

  emits('onSearch', dataOpt);
};

// 监听组件复用
onBeforeRouteUpdate((to) => {
  formData.keyword = (to?.query?.nickname as string) ?? '';
  handleClickSearch();
});

onMounted(() => {
  formData.keyword = (route?.query?.nickname as string) ?? '';
  handleClickSearch();
});
</script>
